package com.hmjk.health.health;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Vector;

import com.hmjk.health.R;





import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Point;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.Typeface;
import android.graphics.Bitmap.Config;
import android.graphics.Paint.FontMetrics;
import android.os.Bundle;
import android.os.Message;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;

public class HealthCardBloodSugarGraph extends Activity {
   
	ImageView mImageView;
	
	public static int mImageViewWidth; //
	public static int mImageViewHeight;  //
	
	public  int mStart_item_idx = 0;
	public  int mLen_items = 10 ;
	public  int mItems1page =10 ;

  static int x_scale_text_fontsize = 18;  //X标字字体
  static int y_scale_text_fontsize = 18;  //Y标字字体
  int x_scale_text_width;   //X标字宽度
  int y_scale_text_width;  //Y标字宽度 
  
  static final String  mMaxScaleTxt ="XX.X";
  
  static int graphtitlefontsize = 26 ;    //标题字体
  int graphtitleheight;      //标题高度
  static int mYScaletextwidth;  //Y刻度最大宽度
  static int mXScaletextHeight;  //X刻度最大高度
  
  static int mGraphgridWidth;  //表格宽度
  static int mGraphgridHeight;  //表格宽度
 
  static int mGraphgriditemwidth;  //表格刻度度说明 宽度
   
  static int mGraphGridLineHeight;  //单表格格子线高度 
  static int mGraphGridLineWidth;  //单表格格子线宽度 

  
  public final int EQUALPROPORTION = 0; 
  public final int GRADEPROPORTION =1; 
  
  public int flagVariableScale = GRADEPROPORTION;   
  
  private  boolean bHideMaxYscale = true;
  
  static Bitmap dotBmap;
  static Bitmap selectdotBmap;	
  
  private static  double minNormalBloodSugar  = 4.4;
  private static  double maxNormalBloodSugar  = 8.0;
  
  
    Bitmap emptyBmap;
    Bitmap charty;
		
	Button mButton1day;        //表格周期
	Button mButton7day;	       //表格周期
	Button mButton14day;        //表格周期 
	Button mButton30day;	     //表格周期
	
	static final int mGridTitleTextColor = Color.BLUE;   //X标字颜色
	static final int mYCoordinateTextColor = Color.DKGRAY;   //Y标字颜色
	static final int mXCoordinateTextColor = Color.DKGRAY;   //X标字颜色
	static final int mGridLineColor = Color.GRAY;   //表格线的颜色
	static final int mGridValueColor = Color.BLUE;   //表格线的颜色
	static final int mGridValuelineColor = Color.RED;   //表格线的颜色
	
	static final int mXCoordinateShortSacleColor = Color.MAGENTA;   //X标字颜色
	
	static final int mGridBackgroundColor=0xFFFFFFFF;        //表格背景颜色
	static final int mGridBackgroundnormalColor=0xFFdcf7d7;  //表格正常区间背景颜色
	
    static Vector data_value =    new Vector();   //测试数据
    static Vector data_x_scale =  new Vector();   //测试数据
    public static Vector data_y_scale =  new Vector();  //测试数据
    static final int total_y_scale = 10;   //Y标尺总刻度
    static final int total_x_scale = 10;   //X标尺总刻度
    
    

    
	
	static int m1pageshowpoints = 10; // 一页显示10个点
    static int selecet_cur_dot = 0;   //X标尺总刻度
	
//	 private OnTouchListener mImageViewTouchListene;
	  // these_labela has elemnes[label,maxX,maxY]
	private static final String TAG = "XXXXXX BloodSugar_Graph";
    static int draw_only_this_idx = -1;
    static int[] drawSizes;
    static int[] graphdrawSizes;
    
	private static final float RMOVE_threshold =(float) 100.0;
	private static final float LMOVE_threshold =(float) -100.0;


	 float   DownX=0;   //检测曲线图移动事件
  	 float   DownY=0;   //检测曲线图移动事件
     float   moveX=0,moveY=0;	//检测曲线图移动事件
	
     
     
     
     static int Getmax_Y_scaletextwidth(String str)
     {   int len=0;
         final Paint paint = new Paint();  
         paint.setTextSize(y_scale_text_fontsize);
         float strwidth = paint.measureText(str);
         len =(int)(strwidth+0.5);
         return len;
     }
   
     static int Getmax_X_scaletextwidth( )
     {   int len=0;
         final Paint paint = new Paint();  
         paint.setTextSize(x_scale_text_fontsize);
         float strwidth = paint.measureText(mMaxScaleTxt);
         len =(int)(strwidth+0.5);
         return len;
     } 
     
     static int Getmax_X_scaletextHeight( )
     { //  int len=0;
         final Paint paint = new Paint();  
         paint.setTextSize(x_scale_text_fontsize);
         FontMetrics fm = paint.getFontMetrics();   
         return (int) Math.ceil(fm.descent - fm.top) + 2;   
   //      return len;
     }     
     
     
     private void resetData()
     {
     	data_value.removeAllElements();
     	data_x_scale.removeAllElements();
     	data_y_scale.removeAllElements();
     }
     

     public void Set_normal_rangofbloodsugar(double min,double max)
     {
    	 minNormalBloodSugar = min;
    	 maxNormalBloodSugar = max;
     }
     
     private void initData()
     {
     	data_value.add("0.0") ;
     	data_value.add("3.0") ;
     	data_value.add("26.0") ;
     	data_value.add("34.0") ;
     	data_value.add("43.0") ;
     	data_value.add("57.0") ;
     	data_value.add("68.0") ;
     	data_value.add("76.0") ;
     	data_value.add("83.0") ;
     	data_value.add("97.0") ;
     	data_value.add("100.0") ;
     	data_value.add("5.2") ;
     	data_value.add("9.6") ;
     	data_value.add("12.2") ;
     	data_value.add("44.2") ;
     	data_value.add("55.2") ;
     	data_value.add("78.2") ;
     	data_value.add("67.6") ;
     	data_value.add("33.2") ;
     	data_value.add("44.2") ;
     	data_value.add("0.2") ;
     	data_value.add("1.2") ;
     	data_value.add("9.6") ;
     	data_value.add("83.2") ;
     	data_value.add("44.2") ;
     	data_value.add("88.2") ;
     	data_value.add("78.2") ;
     	data_value.add("67.6") ;
     	data_value.add("83.2") ;
     	data_value.add("44.2") ; 
     	data_value.add("83.2") ;
     	data_value.add("44.2") ;     	

     	data_x_scale.add("20151026 04:00") ;
     	data_x_scale.add("20151026 07:00") ;
     	data_x_scale.add("20151026 08:00") ;
     	data_x_scale.add("20151026 11:00") ;
     	data_x_scale.add("20151026 13:00") ;
     	data_x_scale.add("20151026 17:00") ;
     	data_x_scale.add("20151026 19:00") ;
     	data_x_scale.add("20151026 22:00") ;
     	data_x_scale.add("20151027 04:00") ;
     	data_x_scale.add("20151027 07:00") ;
     	data_x_scale.add("20151027 08:00") ;
     	data_x_scale.add("20151027 11:00") ;
     	data_x_scale.add("20151027 13:00") ;
     	data_x_scale.add("20151027 17:00") ;
     	data_x_scale.add("20151027 19:00") ;
     	data_x_scale.add("20151027 22:00") ;
     	data_x_scale.add("20151028 04:00") ;
     	data_x_scale.add("20151028 07:00") ;
     	data_x_scale.add("20151028 08:00") ;
     	data_x_scale.add("20151028 11:00") ;
     	data_x_scale.add("20151028 13:00") ;
     	data_x_scale.add("20151028 17:00") ;
     	data_x_scale.add("20151028 19:00") ;
     	data_x_scale.add("20151028 22:00") ;
     	data_x_scale.add("20151029 04:00") ;
     	data_x_scale.add("20151029 07:00") ;
     	data_x_scale.add("20151029 08:00") ;
     	data_x_scale.add("20151029 11:00") ;
     	data_x_scale.add("20151029 13:00") ;
     	data_x_scale.add("20151029 17:00") ;
     	data_x_scale.add("20151029 19:00") ;
     	data_x_scale.add("20151029 22:00") ;    	
  
     	if(data_y_scale.isEmpty())
     	{	
     	  data_y_scale.add("0.0") ;
     	  data_y_scale.add("1.1") ;
     	  data_y_scale.add("2.5") ;
     	  data_y_scale.add("4.0") ;
     	  data_y_scale.add("5.0") ;
     	  data_y_scale.add("6.0") ;
     	  data_y_scale.add("7.0") ;
     	  data_y_scale.add("8.0") ;
     	  data_y_scale.add("9.0") ;
    	  data_y_scale.add("11.0") ; 
     	  data_y_scale.add("15.0") ;    	
    	  data_y_scale.add("33.0") ;    	
     	  data_y_scale.add("99.9") ;
      }    
//         String[] data_y_scale_array = new String[10];
//         data_y_scale_array[0]="0.0";
//         data_y_scale_array[1]="10.0";
//         data_y_scale_array[2]="20.0";   
//         data_y_scale_array[3]="30.0";      	
//         data_y_scale_array[4]="40.0";
//         data_y_scale_array[5]="50.0";   
//         data_y_scale_array[6]="60.0";      	
//         data_y_scale_array[7]="70.0";
//         data_y_scale_array[8]="80.0";   
//        data_y_scale_array[9]="90.0";      	
//         data_y_scale_array[10]="100.0";
//         data_y_scale.add(data_y_scale_array);
     	mYScaletextwidth  = Getmax_X_scaletextwidth();
     	mXScaletextHeight = Getmax_X_scaletextHeight();
     }    
     

     //scr_y 原点坐标   原点坐标在下方 y轴正向朝下

     private static int  get_scale_y( double this_y  , Vector vlist , 
             int scr_y  , int src_height
               )
        {
            int  temp_y;
            double  maxY;
            double  minY;
            double scalecalistart=0;
            double scalecaliend=0; 
            int ncell;
//            Point temp = new Point(); 
            int result=0;
            
            int list_len=0; 
            
            list_len = vlist.size();
            if(0>=list_len)
            {
            	return 0;
            }	
            scalecalistart = getVectorDouble(vlist,0);
            
            if((Double) getVectorDouble(vlist,0)<(Double) getVectorDouble(vlist,list_len-1))
            {
            	//此情况未完整调试 升序
            	maxY = (Double) getVectorDouble(vlist,list_len-1);
            	minY = (Double) getVectorDouble(vlist,0);
            	ncell = list_len;
                for(int i=1;i<list_len;i++)
                {
                	scalecaliend =(Double) getVectorDouble(vlist,i);
                	if((this_y>=scalecalistart)&&(this_y<scalecaliend))
                	{
                		ncell=i-1;
                        try
                        {       int cellh= src_height/list_len;
                                temp_y = scr_y -cellh*ncell - (int)( (this_y-scalecalistart ) * ((double)(cellh)) / (scalecaliend-scalecalistart ) );
                                result= temp_y;
                                 
                                
                        } 
                        catch  (Exception e)
                        {
                     
                           return (0);
                        }                		
                		
                		break;
                	}
                	scalecalistart = scalecaliend;
                }	            	
            }
            else
            {
            	//此情况未完整调试 降序
            	 minY = (Double) getVectorDouble(vlist,list_len-1);
            	 maxY = (Double) getVectorDouble(vlist,0);
            	 ncell = list_len;
                 for(int i=1;i<list_len;i++)
                 {
                 	scalecaliend =(Double) getVectorDouble(vlist,i);
                 	if((this_y<scalecalistart)&&(this_y>=scalecaliend))
                 	{
                 		ncell=i-1;
                        //don't touch it if is nothing
                        try
                        {
                                temp_y = scr_y + (int)( (maxY - this_y) * ((double)src_height / (maxY - minY)) );
                             
                                 
                                result= temp_y;
                                 
                                
                        } 
                        catch  (Exception e)
                        {
                     
                           return (0);
                        }
                        
                 		break;
                 	}
                 	scalecalistart = scalecaliend;
                 }	           	 
           	
            }	
     
            if(ncell == list_len)
            {
            	return 0; //不再区间里面
            }
            
            
            if (maxY <= minY)  //skip bad data
                return 0;


            
            return result;
            
        } // --- end of get_scale_y --          
     
     static Double getVectorDouble(Vector vlist, int arg0)
     {
    	 Double dtmp=0.0;
    	 String str = (String) vlist.elementAt(arg0);
    	 dtmp = Double.parseDouble(str);
    	 return dtmp;
     }
     
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.health_card_bloodsugar_graph_show); 
        setTitle("血糖历史曲线图");
        
         mImageView = (ImageView) findViewById(R.id.bloodsugar_graph_show_img);
     
        WindowManager wm = this.getWindowManager();
        mImageViewWidth = wm.getDefaultDisplay().getWidth();
        mImageViewHeight = wm.getDefaultDisplay().getHeight();
        mImageViewWidth = mImageViewWidth -2;
        mImageViewHeight = mImageViewHeight-2;
        

        
        initData();
        initView();
        setListener();
        
        emptyBmap = Bitmap.createBitmap(mImageViewWidth,
		mImageViewHeight, Config.ARGB_8888);
 
       int width =  emptyBmap.getWidth();
       int height = emptyBmap.getHeight(); 
       
        charty = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
        charty = Show_graph_grid(emptyBmap,mStart_item_idx,mLen_items,mItems1page);
  
        mImageView.setImageBitmap(charty); 


        
        mImageView.setOnTouchListener( mOnTouchListener );
        mImageView.setFocusable(true);
    } 
 
   public void refresh_graph_grid()
   {
	  
       Bitmap emptyBmap1 = Bitmap.createBitmap(mImageViewWidth,
       		mImageViewHeight, Config.ARGB_8888);
       if(mImageView!=null)
       mImageView.setImageBitmap(emptyBmap1);  
       
       int width =  emptyBmap1.getWidth();
       int height = emptyBmap1.getHeight();

       Bitmap charty1 = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
       
       charty1 = Show_graph_grid(emptyBmap,mStart_item_idx,mLen_items,mItems1page);
       
       mImageView.setImageBitmap(charty1); 
       
  
       
   }
    
    
    private void initView()
    {
    	mButton1day =  (Button) findViewById(R.id.tmm_button_1day);
    	mButton7day =  (Button) findViewById(R.id.tmm_button_7day);
    	mButton14day =  (Button) findViewById(R.id.tmm_button_14day);
    	mButton30day = (Button) findViewById(R.id.tmm_button_30day);

    }
  
	private void setListener() {
		mButton1day.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				// 1天血糖曲线
//	       	      Log.d(TAG,"mButton1day.setOnClickListener");

	       		 mStart_item_idx = 0;
	       		 mLen_items = 5 ;
	       		 mItems1page =10 ;
	       	     refresh_graph_grid();
	       	     mButton1day.setBackgroundResource(R.drawable.health_card_bloodsugar_graph_but_selected_bg);
	       	     mButton7day.setBackgroundResource(R.drawable.health_card_bloodsugar_graph_but_bg);
	       	     mButton14day.setBackgroundResource(R.drawable.health_card_bloodsugar_graph_but_bg);
	       	     mButton30day.setBackgroundResource(R.drawable.health_card_bloodsugar_graph_but_bg);
			}
		});
		
		mButton7day.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				
//	       	      Log.d(TAG,"mButton3day.setOnClickListener");
				// 3天血糖曲线
		       		 mStart_item_idx = 0;
		       		 mLen_items = 10 ;
		       		 mItems1page =10 ;
		       		 
		       	     refresh_graph_grid();	       	      
		       	     mButton1day.setBackgroundResource(R.drawable.health_card_bloodsugar_graph_but_bg);
		       	     mButton7day.setBackgroundResource(R.drawable.health_card_bloodsugar_graph_but_selected_bg);
		       	     mButton14day.setBackgroundResource(R.drawable.health_card_bloodsugar_graph_but_bg);
		       	     mButton30day.setBackgroundResource(R.drawable.health_card_bloodsugar_graph_but_bg);
       	      
	       	      
			}
		});	
		
		mButton14day.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				// 7天血糖曲线

	       		 mStart_item_idx = 0;
	       		 mLen_items = 15 ;
	       		 mItems1page =15 ;
	       	     refresh_graph_grid();	 
	       	     mButton1day.setBackgroundResource(R.drawable.health_card_bloodsugar_graph_but_bg);
	       	     mButton7day.setBackgroundResource(R.drawable.health_card_bloodsugar_graph_but_bg);
	       	     mButton14day.setBackgroundResource(R.drawable.health_card_bloodsugar_graph_but_selected_bg);
	       	     mButton30day.setBackgroundResource(R.drawable.health_card_bloodsugar_graph_but_bg);
	       	     
			}
		});	
		
		mButton30day.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				// 15天血糖曲线
	       		 mStart_item_idx = 0;
	       		 mLen_items = 30 ;
	       		 mItems1page =30 ;
	       	     refresh_graph_grid();	
	       	     mButton1day.setBackgroundResource(R.drawable.health_card_bloodsugar_graph_but_bg);
	       	     mButton7day.setBackgroundResource(R.drawable.health_card_bloodsugar_graph_but_bg);
	       	     mButton14day.setBackgroundResource(R.drawable.health_card_bloodsugar_graph_but_bg);
	       	     mButton30day.setBackgroundResource(R.drawable.health_card_bloodsugar_graph_but_selected_bg);
	       	     
			}
		});			
	}
    
    
    


    
    private final View.OnTouchListener mOnTouchListener = new View.OnTouchListener() {
        @Override
        public boolean onTouch(View view, MotionEvent event) {

             switch (event.getAction()) {
            
             case MotionEvent.ACTION_DOWN:
             {
           		DownX = event.getX();//float DownX
          		DownY = event.getY();//float DownY
 //         		downMS = System.currentTimeMillis();//long currentMS
              break;
             }
             case MotionEvent.ACTION_MOVE:
             {
 
         	      
 //        	      Log.d(TAG,"moveX="+moveX+" DownX="+DownX);
 //        	     long moveTime = System.currentTimeMillis() - downMS;   	   

              break;
             }
             case MotionEvent.ACTION_UP:
             {
              //
       		  moveX = event.getX() - DownX;//
     	      moveY = event.getY() - DownY;//
     	      if(moveX>RMOVE_threshold)
     	      {
     	    	  //X move R page
        	      Log.d(TAG,"X move R page"+moveX);
        	      
 	       		 mStart_item_idx = mStart_item_idx+1;
 	       	     refresh_graph_grid();	 	        	      
        	      
     	      }	  
     	      else
     	      if(moveX>0)
     	      {
     	    	 //x Move R one step 
        	      Log.d(TAG,"x Move R one step"+moveX);
  	       		 mStart_item_idx = mStart_item_idx+10;
 	       	     refresh_graph_grid();	

     	      }	  
     	      else
     	      if(moveX>LMOVE_threshold)
     	      {
      	    	 //x Move L one step 
           	      Log.d(TAG,"x Move L one step"+moveX);
        	      if(mStart_item_idx>1)
        	      { 
   	       		     mStart_item_idx = mStart_item_idx-1;
        	      }
 	       	      refresh_graph_grid();

     	      }
     	      else
     	      {
     	    	 // x Move L  page
        	      Log.d(TAG,"X 123 move L page"+moveX);
        	      if(mStart_item_idx>10)
        	      {	  
    	       	    mStart_item_idx = mStart_item_idx-10;
        	      }
     	       	  refresh_graph_grid();
     	      }	  
     	    	             	 
            	 
            	 
              break;
             }
            
             default:
             
              break;
             }       	
        	return true;
        }
        };
    

        private static int GetTextFontHeightInfo(Paint paint,int mFontSize ) {
        	Log.v(TAG,"GetTextFontHeightInfo"+mFontSize);
        	char ch;
        	int h = 0;
        	float moldFontSize;
        	moldFontSize = paint.getTextSize();
        	paint.setTextSize(mFontSize);
       	
        	FontMetrics fm = paint.getFontMetrics();  
          	h = (int) (Math.ceil(fm.descent - fm.top) * 0.9);// 获得字体高度
          	paint.setTextSize(moldFontSize);
          	return h;
        }
        
    public static Bitmap Show_graph_grid(Bitmap bitmap,int item_start,int intem_len,int one_page_total_points)
	  {
		// xode to get bitmap onto screen
	        Bitmap output = Bitmap.createBitmap(bitmap.getWidth(),
	                bitmap.getHeight(), Config.ARGB_8888);
	            Canvas canvas = new Canvas(output);
	         
	            final int color = mGridBackgroundColor; 
	            final Paint paint = new Paint();
	            final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
	            final RectF rectF = new RectF(rect);   
	            final float roundPx = 12;
	         
	            // get the little rounded cornered outside
	            paint.setAntiAlias(true);
	            canvas.drawARGB(0, 0, 0, 0);
	            paint.setColor(color);
	            canvas.drawRoundRect(rectF, roundPx, roundPx, paint);
	            
	            
	            // ---- NOw just draw on this bitmap
	            
	            
	            // Set the labels info manually
	            String[] cur_elt_array = new String[4];
	            cur_elt_array[0]="血糖值";
	            cur_elt_array[1]="mmol/L";
	            cur_elt_array[2]="100";  // max
	            cur_elt_array[3]="0";    //min
	            
	            Vector labels = new Vector();
	            labels.add(cur_elt_array);

	           // Vector yscales = new Vector();
	           // labels.add(cur_elt_array);	            
	            
	            draw_the_grid(canvas,labels,data_y_scale,one_page_total_points);
	 
	            // se the data to be plotted and we should on our way
	            plot_array_list(canvas,data_value,data_x_scale,item_start,intem_len,one_page_total_points);	
	            
	            
	            canvas.drawBitmap(bitmap, rect, rect, paint);
	         
	        return output;
	  }    
    

    
    // these_labels is vector of [label,units,max.min]
  
  
    public static void  draw_the_grid(Canvas this_g,  Vector these_labels,Vector y_scales,int vone_page_total_points)
    {
        
       double rounded_max = 0.0;
       double rounded_min = 0.0;
       double rounded_max_temp;
       Object curElt;  
       String[] cur_elt_array;
       Object curElt_y;  
       String  y_scales_array;
       int left_margin_d, right_margin_d;
      
     

       if( draw_only_this_idx == -1)      
          curElt = these_labels.elementAt(0);  // default  it to 1st one if non set 
       else
          curElt = these_labels.elementAt(draw_only_this_idx);  // now just the 1st elt
          
       cur_elt_array = (String[])curElt;

       
        
       rounded_max = get_ceiling_or_floor (Double.parseDouble(cur_elt_array[2]) , true);
       rounded_min = get_ceiling_or_floor (Double.parseDouble(cur_elt_array[3]) , false);


      // ok so now we have the max value of the set just get a cool ceiling and we go on
       final Paint paint = new Paint();  
       paint.setTextSize(15);
       
      left_margin_d =  getCurTextLengthInPixels(paint, Double.toString(rounded_max));
      //keep the position for later drawing -- leave space for the legend
 
      int titleheight = GetTextFontHeightInfo(paint,graphtitlefontsize );
      int titleheight_space= titleheight;
     
      int p_height = mImageViewHeight -titleheight-mXScaletextHeight-2;
      int p_width = mImageViewWidth;
      int yt=data_y_scale.size();
      int xt= vone_page_total_points;
      m1pageshowpoints = vone_page_total_points;
//      paint.setTextSize(graphtitlefontsize);
    
//      Paint.drawText(cur_elt_array[0],  2, 2) , paint );
      
      int ystep=(p_height);
      if(yt>1) ystep=ystep/yt;
      int xstep=(mImageViewWidth-mYScaletextwidth-2);
      if(xt>1) xstep=xstep/xt;     
 
      mGraphGridLineHeight =ystep;  //单表格格子线高度 
      mGraphGridLineWidth = xstep;  //单表格格子线宽度      
      
      mGraphgridWidth = xt*xstep;
      mGraphgriditemwidth = xstep;
      
      mGraphgridHeight = yt*ystep;
      
      int[] tmp_draw_sizes = {2 , titleheight+titleheight_space+2,2+mYScaletextwidth+mGraphgridWidth  ,(yt-1)*ystep +mXScaletextHeight+titleheight+titleheight_space+2};
      drawSizes = tmp_draw_sizes; //keep it for later processing
      int[] tmp_graph_draw_sizes = {2+mYScaletextwidth , titleheight+titleheight_space+2,2+mYScaletextwidth+mGraphgridWidth  ,(yt-1)*ystep +titleheight+titleheight_space+2};
      graphdrawSizes = tmp_graph_draw_sizes; //keep it for later processing
//      private  double minNormalBloodSugar  = 4.4;
//      private  double maxNormalBloodSugar  = 8.0;
//      int 
      int minnormal;
      int maxnormal;      
      if(!data_y_scale.isEmpty())
      {	  
    
      minnormal =  get_scale_y(minNormalBloodSugar,data_y_scale,graphdrawSizes[3],mGraphgridHeight);
      maxnormal =  get_scale_y(maxNormalBloodSugar,data_y_scale,graphdrawSizes[3],mGraphgridHeight);

      //with the mzrgins worked out draw the plotting grid
      paint.setStyle(Paint.Style.FILL); 
      paint.setColor(mGridBackgroundColor );  
      
      // Android does by coords
      this_g.drawRect(drawSizes[0], drawSizes[1], drawSizes[2], maxnormal , paint);
      paint.setColor(mGridBackgroundnormalColor );  
      
      // Android does by coords
      this_g.drawRect(drawSizes[0], maxnormal, drawSizes[2],minnormal , paint);
      paint.setColor(mGridBackgroundColor );  
      
      // Android does by coords
      this_g.drawRect(drawSizes[0], minnormal, drawSizes[2], drawSizes[3] , paint);

      
      }
      else
      {
    	  
      }	 
    	  
      paint.setColor(mGridLineColor);
      
      
       // finally draw the grid
     
      
//      paint.setStyle(Paint.Style.STROKE); 
 
          for(int i=0; i < yt ; i++)
          {
              this_g.drawRect(graphdrawSizes[0], graphdrawSizes[1] + (i * ystep ),  graphdrawSizes[2], graphdrawSizes[1] + ( i * ystep)+2, paint);


          }
          for(int i=0; i < xt+1 ; i++)
          {

              this_g.drawLine(graphdrawSizes[0]+ (i * xstep ), graphdrawSizes[1] , graphdrawSizes[0] +  (i * xstep ),  graphdrawSizes[3], paint);

          }

          paint.setTextSize(graphtitlefontsize);
          
          paint.setColor( mGridTitleTextColor ); 
    //      paint.setTypeface( Typeface.SANS_SERIF );       
          this_g.drawText(" " +cur_elt_array[0]+"-"+cur_elt_array[1],  drawSizes[0]+mYScaletextwidth,drawSizes[1]-titleheight_space/2, paint );
          
          paint.setTextSize(x_scale_text_fontsize);
          
          paint.setColor( mYCoordinateTextColor ); 

          for(int i=0; i < yt ; i++)
          {
                    curElt_y = (String)y_scales.elementAt(i);
                    y_scales_array = (String)curElt_y; 
                    float strwidth = paint.measureText(y_scales_array);
              this_g.drawText(y_scales_array,  drawSizes[0]+mYScaletextwidth-strwidth,drawSizes[1]+ ((yt-i-1) * ystep ), paint );
          }         
          // good for one value

        
    }  // --- end of draw_grid --- 
    
    


    private static Point  scale_point(int this_x , double this_y  , Point drawPoint , 
            int scr_x  , int scr_y  , int scr_width  , int src_height  , 
            double maxX  , double minX  , double  maxY  , double minY  )
       {
           int temp_x, temp_y;
           Point temp = new Point();   
           
           if (maxY == minY)  //skip bad data
               return null;

           //don't touch it if is nothing
           try
           {
                   temp_x = scr_x + (int)( ((double)this_x - minX) * ((double)scr_width / (maxX - minX)) );
                   temp_y = scr_y + (int)( (maxY - this_y) * ((double)src_height / (maxY - minY)) );
                
                   temp.x = temp_x;
                   temp.y= temp_y;
                   drawPoint = temp;
                   
                   
           } 
           catch  (Exception e)
           {
        
              return (null);
           }
           
           return temp;
           
       } // --- end of scale_point --

//  
    public static boolean plot_array_list(Canvas this_g, Vector this_array_list , Vector x_scales , int vstart  , int vlen,int vone_page_total_points ) 
    {
             int idx;
             int lRow ;
             int nParms;
             int real_xstart;
             int real_xend;
             int real_xlen;
             int real_xstep;
             
             int  i, points_2_plot, shifted_idx ; 
             int prev_x, prev_y ;
             int cur_x=0, cur_y=0 ; 
             //Dim ShowMarker As Object
             Point cur_point = new Point();
            cur_point.set(0,0);
     
             double cur_maxX, cur_minX, cur_maxY=20, cur_minY=0, cur_rangeY;
             int cur_start_x, cur_points_2_plot; 
   
            int POINTS_TO_CHANGE = 30;
            double cur_OBD_val;
  
             //Object curElt;  
             String curElt; 
             String cur_elt_array;
             Object curElt_xscal;  
             String cur_elt_array_xscal;
     
             final Paint paint = new Paint();

             try // catch in this block for some thing
             {
       
                   points_2_plot = this_array_list.size();
                   {
                        cur_start_x = 0;
                        cur_points_2_plot = points_2_plot;
                        cur_maxX = cur_points_2_plot;
                        cur_minX = 0;
                        if((vstart>cur_start_x)&&(vstart<cur_points_2_plot))
                       	{
                        	real_xstart = vstart;
                        }
                        else
                        {
                        	real_xstart = cur_start_x;
                        }
                        if(vlen>vone_page_total_points)
                        {
                        	real_xlen =vone_page_total_points;
                        }	
                        else
                        {
                        	real_xlen = vlen;
                        }	
                        
                        if(vstart+real_xlen<points_2_plot)
                        {
                        	real_xend =vstart+real_xlen;
                        }
                        else
                        {
                        	real_xend = points_2_plot;
                        	real_xlen = real_xend-vstart;
                        }	
                        
                   }
                   int yscalemaxtextwidth=0;
                   int tmplen;
                   for (i = real_xstart ; i< real_xend ; i++)
                   {
                	   curElt_xscal =(String)x_scales.elementAt(i);
                	   cur_elt_array_xscal = (String) curElt_xscal;
                	   tmplen =Getmax_Y_scaletextwidth(cur_elt_array_xscal);
                	   if(tmplen>yscalemaxtextwidth)
                	   {
                		   yscalemaxtextwidth =tmplen;
                	   } 
                   }
                   
                  int tmp_total_scale_item_width = real_xlen*mGraphgriditemwidth;
                  if((tmp_total_scale_item_width/(yscalemaxtextwidth+1))>real_xlen)
                  {
                	  real_xstep = 1; 
                  }
                  else
                  {
                	  real_xstep = tmp_total_scale_item_width/(yscalemaxtextwidth+1);
                	  real_xstep = real_xlen/real_xstep+1;
 //               	  if(1==real_xstep) real_xstep=2;
                  }	  
      
                  paint.setTextSize(y_scale_text_fontsize);
                  
  //                paint.setColor( mYCoordinateTextColor ); 
  //                paint.setTypeface( Typeface.SANS_SERIF );       

                  for (i = real_xstart ; i< real_xend ; i+=real_xstep)
                  {
                  	   curElt_xscal =(String)x_scales.elementAt(i);
                	   cur_elt_array_xscal = (String) curElt_xscal;
                       paint.setColor( mYCoordinateTextColor ); 
                       paint.setTypeface( Typeface.SANS_SERIF ); 
                       this_g.drawText(cur_elt_array_xscal,  drawSizes[0]+mYScaletextwidth+(i-real_xstart)*mGraphgriditemwidth,drawSizes[3], paint );
                       paint.setColor(mXCoordinateShortSacleColor);
                       paint.setStyle(Paint.Style.STROKE); 
                       //画短刻度线
                       this_g.drawLine(drawSizes[0]+mYScaletextwidth+(i-real_xstart)*mGraphgriditemwidth, graphdrawSizes[3]-30 , drawSizes[0]+mYScaletextwidth+(i-real_xstart)*mGraphgriditemwidth,  graphdrawSizes[3], paint);
                      
                  }	  
                
                   //'Create the plot points for this series from the ChartPoints array:
   
                   curElt = (String)this_array_list.elementAt(0);
                   
                   //the lines have to come out good
                    paint.setStyle(Paint.Style.STROKE);
//                  
                   //for(  nParms = 0 ; nParms < cur_elt_array.length ; nParms++ )
                //   nParms = only_this_idx;
                   {
    
                       //get cur item labels
                  //      curElt2 = these_labels.elementAt(nParms);
                 //      cur_elt_array2  = (String[]) curElt2;
                        
                        cur_maxY = 100.0;  //get_ceiling_or_floor (Double.parseDouble(cur_elt_array2[2]) , true);
                        cur_minY = 0.0;    //get_ceiling_or_floor (Double.parseDouble(cur_elt_array2[3]) , false);
                        
                        cur_points_2_plot = this_array_list.size();                     
                        cur_maxX = cur_points_2_plot;
                        if(cur_points_2_plot>vlen) 	cur_maxX = vlen;  //总共有多少横点待计算
                        cur_maxX = real_xend;
                        cur_minX = real_xstart;
                        
                      curElt = (String)this_array_list.elementAt(0);
                      cur_OBD_val = Double.parseDouble( curElt);
                      
                      cur_point = scale_point(0, cur_OBD_val, cur_point, 
                    		  graphdrawSizes[0], graphdrawSizes[1], graphdrawSizes[2]-graphdrawSizes[0], graphdrawSizes[3]-graphdrawSizes[1], 
                              cur_maxX, cur_minX, cur_maxY, cur_minY); //'(CInt(curAxisValues.Mins(nParms - 2) / 5) + 1) * 5)
                       
                       cur_x = cur_point.x;
                       cur_y = cur_point.y;

                       
                      // the point is only cool when samples are low
                       if ( cur_points_2_plot < POINTS_TO_CHANGE)
                         this_g.drawRect(cur_x-2, cur_y-2, cur_x-2 + 4,cur_y-2+ 4 , paint); 
                       
                       prev_x = cur_x;
                       prev_y = cur_y;

                      

                       //'go and plot point for this parm -- pont after the 1st one 
                       for (lRow = real_xstart ; lRow< real_xend+1 ; lRow++)
                       {
        
                           curElt = (String)this_array_list.elementAt(lRow);
                           
                           cur_OBD_val = Double.parseDouble( curElt);
                             
                           
                                 
                                 
                            //'work out an approx if cur Y values not avail(e.g. nothing)
                           // if (! (cur_elt_array[nParms ] == null ) )   //skip bad one
                             if( cur_OBD_val == Double.NaN) continue;  //skip bad one
                            {                  
       
                               
                                cur_point=scale_point(lRow, cur_OBD_val, cur_point,  
                                		graphdrawSizes[0], graphdrawSizes[1], graphdrawSizes[2]-graphdrawSizes[0], graphdrawSizes[3]-graphdrawSizes[1], 
                                    cur_maxX, cur_minX, cur_maxY, cur_minY);
    
                                cur_x = cur_point.x;
                                cur_y = cur_point.y;
                                
                                paint.setColor(mGridValueColor);
                                    
                        //        if ( cur_points_2_plot < POINTS_TO_CHANGE)
                     //              this_g.drawRect(cur_x-2, cur_y-2, cur_x-2 +4, cur_y-2 + 4, paint ); 
                                if(dotBmap.getByteCount()>0)
                                this_g.drawBitmap(dotBmap, cur_point.x-dotBmap.getWidth()/2, cur_point.y-dotBmap.getHeight(), paint);

                                if(selecet_cur_dot==lRow-real_xstart)
                                {
                                    if(selectdotBmap.getByteCount()>0)
                                        this_g.drawBitmap(selectdotBmap, cur_point.x-selectdotBmap.getWidth()/2, cur_point.y-selectdotBmap.getHeight(), paint);
                                }	
                                paint.setColor(mGridValuelineColor);
//画竖线
                               this_g.drawLine( cur_x-1, graphdrawSizes[3], cur_x-1, cur_y, paint);
                               this_g.drawLine( cur_x, graphdrawSizes[3], cur_x, cur_y, paint);
                               this_g.drawLine( cur_x+1, graphdrawSizes[3], cur_x+1, cur_y, paint);

                               prev_x = cur_x;
                               prev_y = cur_y;
                                                        
                            } // ' if end of this_array(lRow, nParms - 1)<> nothing
                                 
                   } // end of for lrow
                               
               } // end of for nParmns


            //this_g.invalidate();
            return( true);
        }
        catch (Exception e)
        {
            return( false);
            
        }

    } // --- end of plot_array_list  --

    
    
    
    
    
    
    

 
    
    
    
    // need the width of the labels
    private static int getCurTextLengthInPixels(Paint this_paint, String this_text) {
        FontMetrics tp = this_paint.getFontMetrics();
        Rect rect = new Rect();
        this_paint.getTextBounds(this_text, 0, this_text.length(), rect);
       return rect.width();
    } // --- end of getCurTextLengthInPixels  ---

    
    public static double get_ceiling_or_floor(double this_val ,  boolean is_max  )
    {
        double this_min_tmp;
        int  this_sign;
        int  this_10_factor=0;
        double this_rounded;

        if (this_val == 0.0) 
        {
            this_rounded = 0.0;
            return this_rounded;
        }

        this_min_tmp = Math.abs(this_val);

        if (this_min_tmp >= 1.0 && this_min_tmp < 10.0) 
            this_10_factor = 1;
        else if (this_min_tmp >= 10.0 && this_min_tmp < 100.0) 
            this_10_factor = 10;
        else if (this_min_tmp >= 100.0 && this_min_tmp < 1000.0) 
            this_10_factor = 100;
        else if (this_min_tmp >= 1000.0 && this_min_tmp < 10000.0) 
            this_10_factor = 1000;
        else if (this_min_tmp >= 10000.0 && this_min_tmp < 100000.0) 
            this_10_factor = 10000;
       


        //'cover when min is pos and neg
        if (is_max) 
        {
            if (this_val > 0.0) 
                this_sign = 1;
            else
                this_sign = -1;
            
        }    
        else
        {
            if (this_val > 0.0) 
                this_sign = -1;
            else
                this_sign = 1;
            
        }


        if (this_min_tmp > 1) 
            this_rounded = (double)(((int)(this_min_tmp / this_10_factor) + this_sign) * this_10_factor);
        else
        {
            this_rounded = (int)(this_min_tmp * 100.0);
            //' cover same as above bfir number up to .001 less than tha it will skip
            if (this_rounded >= 1 && this_rounded < 9) 
                this_10_factor = 1;
            else if (this_rounded >= 10 && this_rounded < 99) 
                this_10_factor = 10;
            else if (this_rounded >= 100 && this_rounded < 999) 
                this_10_factor = 100;
            
            this_rounded = (double)(((int)((this_rounded) / this_10_factor) + this_sign) * this_10_factor);
            this_rounded = (int)(this_rounded) / 100.0;

        }

        if (this_val < 0) 
          this_rounded = -this_rounded;
          
        return  this_rounded;

} // --- end of get_ceiling_or_floor ---

	@Override
	public void onResume(){
		super.onResume();
		

	}
	
	@Override
	public void onPause(){
		super.onPause();
		
		resetData();
	}
 
    
    
	@Override
	public void onDestroy(){
		super.onDestroy();
		resetData();
	}    
    
}